package exampleQuestions;

public class QueenProblem {
	
	static int resultCounter = 0;

	/**
	 */
	public static void main(String[] args) {

		int[] tab = { -1, -1, -1, -1, -1, -1, -1, -1 };
		solveQueensProblem(0, 8, tab);

		System.out.println(resultCounter);
	}

	private static void solveQueensProblem(int i, int n, int[] tab) {
		if (i == n) {
			printResult(tab);
		} else {
			for (int j = 0; j < n; j++) {
				if (isColumnValid(i, j, tab) && checkDiagonals(i, j, tab)) {
					tab[i] = j;
					solveQueensProblem(i + 1, n, tab);
					tab[i] = -1;
				}
			}
		}
	}

	private static boolean isColumnValid(int i, int j, int[] tab) {

		for (int k = 0; k < i; k++) {
			if (tab[k] == j) {
				return false;
			}
		}
		return true;
	}

	private static boolean checkDiagonals(int i, int j, int[] array) {

		boolean result = true;
		for (int index = -7; index < 8; index++) {
			
			int posX = j + index;
			int posY = i + index;
			
			if(!checkCondition(posX, posY, array)) {
				result = false;
				break;
			}
			
			posX = j - index;
			posY = i + index;
			
			if(!checkCondition(posX, posY, array)) {
				result = false;
				break;
			}
			
		}

		return result;
	}

	private static boolean checkCondition(int posX, int posY, int[] array) {
		if (posX >= 0 && posX < 8 && posY >= 0 && posY < 8) {
			if (array[posY] == posX) {
				return false;
			}
		}
		return true;
	}

	private static void printResult(int[] array) {
		
		resultCounter++;
		
		for (int i = 0; i < array.length; i++) {
			System.out.print("(" + i + "," + array[i] + ") ");
		}
		System.out.println();
	}

}
